package xyz.jiang.business.filter;


import cn.hutool.core.util.StrUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import xyz.jiang.common.utils.RedisUtils;
import xyz.jiang.common.utils.UserHolder;

import java.io.IOException;

import static xyz.jiang.common.constants.TokenConstants.TOKEN_PREFIX;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class UserFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        String userId = (String) RedisUtils.get(TOKEN_PREFIX + token);
        if (!StrUtil.isBlank(userId)) {
            UserHolder.setUserId(userId);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

